package sync;

/*
* 两个储户分别向同一个账户存3000,每次存1000,存完打印余额
*
* 分析:
* 1:是否多线程:是两个储户线程
* 2:是否有共享数据:有,一个账户
* 3:是否有线程安全问题,有
* 4:考虑用哪种方式同步执行,同步机制的三种
* */

import java.util.concurrent.locks.ReentrantLock;

class Account{
    Double balance;
    ReentrantLock lock = new ReentrantLock();

    public Account(Double balance) {
        this.balance = balance;
    }
    //存钱方法
//    方式1:使用synchronized修饰的同步方法
//    public synchronized void deposit(double amt){
    public void deposit(double amt){
//    方式2:使用ReentrantLock对象加锁

        lock.lock();
        if (amt > 0){

            balance += amt;

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ":存钱成功,余额为:" + balance);
        }
        lock.unlock();
    }
}

class Customer extends Thread{
    private Account account;

    public Customer(Account account){
        this.account = account;
    }

    @Override
    public void run() {

        for (int i = 0; i < 3; i++) {
            account.deposit(1000);
        }

    }
}

public class AccountTest {

    public static void main(String[] args) {
        Account acct = new Account((double) 0);

        Customer c1 = new Customer(acct);
        Customer c2 = new Customer(acct);

        c1.setName("张三");
        c2.setName("李四");

        c1.start();
        c2.start();
    }



}
